package com.indusfo.spc.controller;


import com.indusfo.spc.aspect.SystemControllerLog;
import com.indusfo.spc.pojo.Dosing;
import com.indusfo.spc.pojo.ExcelErrorData;
import com.indusfo.spc.pojo.Mat;
import com.indusfo.spc.service.DosingService;
import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 叫料信息控制层
 */

@Controller
@RequestMapping("/service/dosing")
public class DosingController {

    @Autowired
    private DosingService dosingService;
    
    
    /**
     * 编辑
     *
     * @param dosing
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value = "/updateDosing",method= RequestMethod.POST)
    @SystemControllerLog(description="编辑叫料信息")
    @ResponseBody
    public JSONObject updateDosing (Dosing dosing){
        JSONObject json=dosingService.updateDosing(dosing);
        return json;
    }

    /**
     * 查询
     *
     * @param dosing
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value="/queryDosing")
    @SystemControllerLog(description="查询叫料信息")
    @ResponseBody
    public JSONObject queryDosing(Dosing dosing) {
        JSONObject json = dosingService.selectAll(dosing);
        return json;

    }

    /**
     * 新增
     *
     * @param dosing
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value="/insertDosing", method= RequestMethod.POST)
    @SystemControllerLog(description="新增叫料信息")
    @ResponseBody
    public JSONObject insertDosing(Dosing dosing) {
        JSONObject json = dosingService.insertDosing(dosing);
        return json;
    }

    /**
     * 启用/停用
     *
     * @param dosingIds, dataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value="/definedDosing", method= RequestMethod.POST)
    @SystemControllerLog(description="启用/停用叫料信息")
    @ResponseBody
    public JSONObject definedDosing(Long[] dosingIds, Integer dataState) {
        JSONObject json = dosingService.definedDosing(dosingIds, dataState);
        return json;
    }

    /**
     * 删除
     *
     * @param dosingIds, dataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @RequestMapping(value="/deleteDosing", method= RequestMethod.POST)
    @SystemControllerLog(description="删除叫料信息")
    @ResponseBody
    public JSONObject deleteDosing(Long[] dosingIds, Integer dataState) {
        dataState = 2;
        JSONObject json = dosingService.definedDosing(dosingIds, dataState);
        return json;
    }


    @RequestMapping("uploadFileDosing")
    @ResponseBody
    public JSONObject uploadFileDosing(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //定义一个message对象用于向前台传输数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.setStatus(JSONObject.SUCCESS);

        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            jsonObject.setStatus(JSONObject.ERROR);
            jsonObject.setMsg("文件解析错误");
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    jsonObject.setStatus(JSONObject.ERROR);
                    jsonObject.setMsg("未找到需要导入的数据，请确认物料信息表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认料信息表格是否保存！！！"));
                } else {
                    List<Dosing> dosingList = new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        //产品编码
                        String productCode = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                        //工序名称
                        String proName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
                        //物料编码
                        String bomCode =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
                        Dosing dosing = new Dosing(productCode,proName,bomCode);
                        //将excel中的每一行数据存储进行检查
                        String result = dosingService.checkExcelContent(dosing);
                        if (result != null) {
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
                            needAdd = false;
                        }
                        if (needAdd) {
                            dosingList.add(dosing);
                        } else {
                            jsonObject.setStatus(JSONObject.ERROR);
                            jsonObject.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (jsonObject.getStatus().equals(JSONObject.ERROR) && !way) {
                        jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
                    } else {
                        if (dosingList.size() > 0) {
                            try {
                                dosingService.updateListDosing(dosingList);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                                if ("导入成功".equals(jsonObject.getMsg())) {
                                    jsonObject.setStatus(JSONObject.SUCCESS);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonObject.setMsg("导入失败");
                            }
                        }
                    }
                }
            }
        }
        jsonObject.setData(GsonUtil.toJson(errorDatas));
        //response.getWriter().println(GsonUtil.toJson(msg));
        return JSONObject.build(JSONObject.SUCCESS, jsonObject.getMsg(), errorDatas);
    }
}
